<template>
  <div class="home">
    <nav-bar></nav-bar>
    <van-tabs v-model="active" sticky  :offset-top="50" animated>
      <van-tab
        v-for="(item, index) in category"
        :key="index"
        :title="item.title"
      >
        <van-list
          v-model="item.loading"
          :finished="item.finished"
          finished-text="我是有底线的 >_<"
          @load="onLoad"
          :immediate-check="false"
          :offset="200"
        >
          <van-cell>
            <div
              class="main-list"
              v-for="(item, index) in item.list"
              :key="index"
              @click="$router.push(`/article/${item.id}`)"
            >
              <img :src="item.img" alt="" />
              <p>{{ item.name }}</p>
            </div>
          </van-cell>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import NavBar from "../components/common/NavBar";
// import fn from "../function/thorrot";
export default {
  name: "Home",
  data() {
    return {
      active: "",
      category: [],
    };
  },
  components: {
    NavBar,
  },
  methods: {
    async getCategory() {
      const res = await this.$http.get("/category");
      // 给每个分类都初始化参数，使之不互相干扰
      this.category = res.data.map((item) => {
        item.list = [];
        item.page = 0;
        item.loading = false;
        item.finished = false;
        return item;
      });
    },
    async getArticle() {
      let item = this.category[this.active];
      const res = await this.$http.get("/detail/" + item._id, {
        params: {
          page: item.page,
          pagesize: 20,
        },
      });
      // 如果是page为0时让数据覆盖，避免重复push
        item.list.push(...res.data);
      if (res.data.length < 20) {
        item.finished = true;
      }
    },
    async onLoad() {
      const item = this.category[this.active];
      item.page += 1;
      this.getArticle();
      // loading会连续变化两次，必须设置定时器
      setTimeout(() => {
        item.loading = false;
      }, 500);
    },
  },
  watch: {
    active() {
      const item = this.category[this.active];
      item.page = 0
      item.list=[]
      this.getArticle();
    },
    
  },
  created() {
    this.getCategory();
  },
};
</script>

<style lang="less">
.van-cell {
  padding: 5px;
  margin-top: 50px;
  .van-cell__value {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .main-list {
      width: 49%;
      height: 100px;
      margin-bottom: 65px;
      img {
        width: 100%;
        height: 110px;
      }
      p{
        font-size: 14px;
      }
    }
  }
}
</style>
